#include <stdio.h>
#include "main.h"
#include <string.h>

int readdata(FILE* file, struct contact data[], int* p_index);

int initfile(FILE* file, struct contact data[], int* p_index, int is_text)
{
	int ret, ret_fread;
	puts("Initializing file.");
	if (is_text == TRUE){
		printf("*p_index = %d\n", (*p_index));
		do 
		{
			ret = readdata(file, data, p_index);
			printf("*index = %d\n", (*p_index));
		} while (ret != 1);
		printf("%d contacts added.\n", (*p_index));
	} 
	else {
		while ((ret_fread = (fread(&data[*p_index], sizeof(struct contact), 1, file))) > 0){
			printf("ret_fread = %d\n", ret_fread);
			(*p_index)++;
		}
	}
	fclose(file);
	return 0;
}

int readdata(FILE* file, struct contact data[], int* p_index)
{
	int i, c;
	char r;
//	puts("Inside readdata");
//	printf("*p_index = %d\n", (*p_index));
	c = fgetc(file);
	if (c != EOF){
		i = 0;
		do {
			data[*p_index].name[i] = c;
			c = fgetc(file);
			i++;
		} while (c != '\n');
		data[*p_index].name[i] = '\0';
//		printf("j = %d\n", i);

		fscanf(file, "%d", &(data[*p_index].age));
		fscanf(file, "%c", &r);

		i = 0;
		while ((c = fgetc(file)) != '\n'){
			data[*p_index].tel[i] = c;
			i++;
		} 
		data[*p_index].tel[i] = '\0';
//		printf("c = %d\n", c);
//		printf("i = %d\n", i);
		(*p_index)++;
		return 0;
	}
	else {
		return 1;
	}
}
